package com.ln.adoms.action;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.ln.adoms.entity.*;
import com.ln.adoms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ln.adoms.entity.neum.Status;
import com.ln.adoms.vo.ScanGoodsVO;
import com.ln.core.orm.Filtration;
import com.ln.core.orm.Filtration.MatchType;
import com.ln.core.orm.PageData;
import com.ln.core.security.entity.Users;
import com.ln.core.utils.WebUtils;

@Controller
@RequestMapping("/adoms/reback")
public class RebackAction extends BaseAction {
    @Resource
    private OrderService orderService;
    @Resource
    private MarchandiseService marchandiseService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private BrandService brandService;
    @Resource
    private GoodsService goodsService;

    @Autowired
    private QrBoxCodeService qrBoxCodeService;
    @Autowired
    private QrGoodsCodeService qrGoodsCodeService;

    @RequestMapping("/list")
    public ModelMap list(HttpServletRequest request) {
        PageData<Order> pageData = new PageData<Order>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        pageData.getFiltrations().add(new Filtration(MatchType.EQ, false, "type"));
        pageData = orderService.find(pageData);
        return new ModelMap(pageData);
    }

    @RequestMapping("/myReturnsList")
    public ModelMap myOrderList(HttpServletRequest request) {
        PageData<Order> pageData = new PageData<Order>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        Filtration filter = new Filtration(MatchType.EQ, getCurrentUser(request).getDepartment().getId(), "department.id");
        Filtration ftype = new Filtration(MatchType.EQ, false, "type");
        pageData.getFiltrations().add(filter);
        pageData.getFiltrations().add(ftype);
        pageData = orderService.find(pageData);
        return new ModelMap(pageData);
    }

    @RequestMapping("/dealReturnsList")
    public ModelMap dealOrderList(HttpServletRequest request) {
        PageData<Order> pageData = new PageData<Order>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        Filtration filter = new Filtration(MatchType.EQ, getCurrentUser(request).getDepartment().getId(), "departmentTarget.id");
        Filtration ftype = new Filtration(MatchType.EQ, false, "type");
        pageData.getFiltrations().add(filter);
        pageData.getFiltrations().add(ftype);
        pageData = orderService.find(pageData);
        return new ModelMap(pageData);
    }

    @RequestMapping(value = "/returns", method = RequestMethod.GET)
    public String order(Model model, HttpServletRequest request) {
        commonOrder(model, request);
        return "/adoms/reback/returns";
    }

    private void commonOrder(Model model, HttpServletRequest request) {
        List<Marchandise> mList = new ArrayList<Marchandise>();
        List<Marchandise> mAll = marchandiseService.findAll();
        Integer did = getCurrentUser(request).getDepartment().getId();
        List<Brand> allBrand = brandService.findAll();
        Set<Brand> myBrands = new HashSet<Brand>();
        for (Brand b : allBrand) {
            Set<Department> departs = b.getDepartment();
            for (Department d : departs) {
                if (d.getId().equals(did)) {
                    myBrands.add(b);
                }
            }
        }
        // 只取代理的品牌下面的代理商品
        for (Marchandise m : mAll) {
            for (Brand b : myBrands) {
                if (b.getId().equals(m.getBrand().getId())) {
                    if (!mList.contains(m)) {
                        mList.add(m);
                    }
                }
            }
        }

        model.addAttribute("mList", mList);
        List<Department> dList = departmentService.findByParentID(did);
        model.addAttribute("dList", dList);
    }

    @RequestMapping(value = "/returns", method = RequestMethod.POST)
    public String order(Model model, Order order, OrderLine orderLine, Integer[] goodsId, HttpServletRequest request) {

        Integer departmentId = this.getCurrentDepartmentId(request);
        Users user = this.getCurrentUser(request);
        orderService.returnsOrder(model, orderLine, order, user, request, departmentId, goodsId);
        // commonOrder(model, request);
        return "/adoms/reback/returns";
    }

    @RequestMapping(value = "/myEdit/{id}")
    public String myEdit(@PathVariable("id") Integer id, Model model) {
        Order order = orderService.find(id);
        model.addAttribute(order);
        return "/adoms/reback/myInput";
    }

    @RequestMapping(value = "/myDelete/{id}")
    public String myDelete(@PathVariable("id") Integer id) {
        orderService.delete(id);
        return "redirect:/adoms/reback/myOrderList";// 重定向
    }

    @RequestMapping(value = "/mySave", method = RequestMethod.POST)
    public String mySave(Order order) {
        order.setType(false);// 退货
        if (order.isNew()) {
            orderService.save(order);
        } else {
            orderService.update(order);
        }
        try {
            if (order.getStatus().equals(Status.ORDER_HAS_RECEIPT)) {
                List<Goods> list = goodsService.findList("from Goods where department.id=? and order.id=?", order.getDepartmentTarget().getId(), order.getId());
                for (Goods o : list) {
                    Goods g = o.clone(o);
                    g.setDepartment(order.getDepartment());
                    g.setState(Status.WILL_SALE.getValue());
                    g.setOrder(null);
                    goodsService.save(g);
                }

                return "redirect:/adoms/goods/orderGoods?orderId=" + order.getId();// 重定向
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/adoms/reback/myReturnsList";// 重定向
    }

    @RequestMapping(value = "/view/{id}")
    public String viewOrder(@PathVariable("id") Integer id, Model model) {
        Order order = orderService.find(id);
        model.addAttribute(order);
        List<Goods> goodsList = goodsService.findList("order.id", order.getId());
        model.addAttribute("goodsList", goodsList);
        return "/adoms/reback/view";
    }

    @RequestMapping(value = "/valid")
    @ResponseBody
    public Map<String, Object> validGoods(Integer departmentID, Integer marchandiseID, String qrCode) {
        Map<String, Object> rdata = new HashMap<String, Object>();


        qrCode = qrCode.trim().replace(" ", "");
        String msg = checkGoodsQrCode(qrCode, departmentID, marchandiseID);
        if (msg != null) {
            rdata.put("error", msg);
            return rdata;
        }
        Map<String, Object> result = null;
        //先按单件货物查询
        String hql = "from Goods where department.id = ? and marchandise.id = ? and qrCode.qrCode = ?";
        List<Goods> list = goodsService.findList(hql, departmentID, marchandiseID, qrCode);
        if (list == null || list.isEmpty()) {
            //单个未查到就按一箱来查询
            hql = "from Goods where department.id = ? and marchandise.id = ? and qrCode.box.qrCode = ?";
            list = goodsService.findList(hql, departmentID, marchandiseID, qrCode);
        }

        if (list != null && !list.isEmpty()) {
            List<ScanGoodsVO> voList = new ArrayList<ScanGoodsVO>();
            for (Goods g : list) {
                voList.add(new ScanGoodsVO(g));
            }
            result = new HashMap<String, Object>();
            result.put("goods", voList);
        }
        rdata.put("data", result);

        return rdata;
    }

    private String checkGoodsQrCode(String qrCode, Integer departmentID, Integer marchandiseID) {
        List<Goods> goodsList = goodsService.findList("from Goods where qrCode.qrCode = ? and 1 = ?", qrCode, 1);
        boolean isDepart = false, isMarch = false;
        if (goodsList != null || goodsList.isEmpty()) {
            QrBoxCode qrBoxCode = qrBoxCodeService.find("qrCode", qrCode);
            if (qrBoxCode != null) {
                List<QrGoodsCode> qrGoodsCodeList = qrGoodsCodeService.findList("box.id", qrBoxCode.getId());
                if (qrGoodsCodeList != null && !qrGoodsCodeList.isEmpty()) {
                    goodsList = new ArrayList<Goods>();
                    for (QrGoodsCode qrGoodsCode : qrGoodsCodeList) {
                        List<Goods> gs = goodsService.findList("from Goods where qrCode.id = ? and 1 = ?", qrGoodsCode.getId(), 1);
                        if (gs != null && !gs.isEmpty()) {
                            goodsList.addAll(gs);
                        }
                    }

                }
            }
        }
        for (Goods goods : goodsList) {
            if (!isDepart) {
                if (goods.getDepartment().getId().equals(departmentID)) {
                    isDepart = true;
                }
            }
            if (!isMarch) {
                if (goods.getMarchandise().getId().equals(marchandiseID)) {
                    isMarch = true;
                }
            }
        }


        if (!isDepart) {
            return "D";
        } else if (!isMarch) {
            return "M";
        }
        return null;
    }

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    }

}